import 'dart:convert';
import 'dart:io';

import 'package:cave_flutter/whl_app.dart';
import 'package:cave_flutter/db_manager/bean/whl_product_bean.dart';
import 'package:cave_flutter/style/whl_style.dart';
import 'package:cave_flutter/utils/whl_date_utils.dart';
import 'package:cave_flutter/utils/whl_user_utils.dart';
import 'package:cave_flutter/widgets/brick/brick.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';


import 'bottom_controll_view/whl_bottom_control_view_view.dart';
import 'whl_product_detail_logic.dart';

class WhlProductDetailPage extends StatelessWidget {
  WhlProductDetailPage({Key? key}) : super(key: key);

  final logic = Get.put(WhlProductDetailLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Stack(
        children: [
          UIColumn(
            onTap: () {
              hideKeyboard(context);
            },
            children: [
              Expanded(
                child: CustomScrollView(
                  controller: logic.scrollController,
                  slivers: [
                    buildProductDetailView(),
                    buildCommentView(),
                    SliverToBoxAdapter(
                      child: Container(
                        height: 20.h,
                      ),
                    )
                  ],
                ),
              ),
              WhlDetailBottomView(),
            ],
          ),
          buildTopBar(),
          GetBuilder<WhlProductDetailLogic>(builder: (logic) {
            return Visibility(
                visible: logic.giftVisible,
                child: Container(
                  alignment: Alignment.center,
                  color: const Color(0x80000000),
                  child: Opacity(
                    opacity: logic.giftAlpha,
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        UIImage(
                          assetImage: logic.selectedGift,
                        )
                      ],
                    ),
                  ),
                ));
          }),
        ],
      ),
    );
  }

  GetBuilder<WhlProductDetailLogic> buildCommentView() {
    return GetBuilder<WhlProductDetailLogic>(builder: (logic) {
      return SliverList(
          delegate: SliverChildBuilderDelegate((context, index) {
        WhlCommentModel model = logic.productBean.commentList!.reversed.toList()[index];
        bool isLast = (index == logic.productBean.commentList!.length - 1);
        return UIColumn(
          margin: EdgeInsets.symmetric(horizontal: 20.w),
          padding: EdgeInsets.only(left: 12.w, right: 12.w, top: 12.h),
          color: kAppColor('#F6F6F6'),
          radius: 4.w,
          children: [
            UIRow(
              children: [
                UIImage(
                  httpImage: model.avatar ?? '',
                  width: 38.w,
                  height: 38.w,
                  radius: 19.w,
                  fit: BoxFit.cover,
                ),
                UIText(
                  margin: EdgeInsets.only(left: 10.w),
                  text: model.nickname ?? '',
                  textColor: kAppTextColor,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.bold,
                ),
                Expanded(child: Container()),
                UIImage(
                  assetImage: model.isLike == true ? 'icon_like.png' : 'icon_like_no.png',
                  width: 16.w,
                  onTap: () {
                    logic.doClickCommentLike(model);
                  },
                )
              ],
            ),
            UIText(
              margin: EdgeInsets.symmetric(vertical: 12.h),
              alignment: Alignment.centerLeft,
              text: model.content,
              textColor: kAppTextColor,
              fontSize: 12.sp,
            ),
            UIText(
              margin: EdgeInsets.symmetric(vertical: 5.h),
              alignment: Alignment.centerRight,
              text: WhlDateUtils.getTimeStringFromWechat(model.time ?? 0),
              textColor: kAppSub2TextColor,
              fontSize: 12.sp,
            ),
            if (!isLast)
              Container(
                margin: EdgeInsets.symmetric(vertical: 12.h),
                height: 0.5.w,
                color: kAppColor('#CCCCCC'),
              )
          ],
        );
      }, childCount: logic.productBean.commentList?.length ?? 0));
    });
  }

  buildProductDetailView() {
    return GetBuilder<WhlProductDetailLogic>(builder: (logic) {
      String? titleTranslated;
      String? describeTranslated;
      if (logic.productBean.extra?.isNotEmpty ?? false) {
        Map map = jsonDecode(logic.productBean.extra!);
        titleTranslated = map['titleTranslatedText'];
        describeTranslated = map['describeTranslatedText'];
      }
      return SliverToBoxAdapter(
        child: UIColumn(
          margin: EdgeInsets.only(top: ScreenUtil().statusBarHeight+ 44.h),
          color: Colors.white,
          children: [
            Stack(
              children: [
                Container(
                  width: double.maxFinite,
                  constraints: BoxConstraints(
                    maxHeight: 400.h,
                  ),
                  child: GetBuilder<WhlProductDetailLogic>(builder: (logic) {
                    return Swiper(
                        itemCount: (logic.productBean.details?.length ?? 0) + 1,
                        itemBuilder: (context, index) {
                          if (index == 0) {
                            if (logic.productBean.cover?.contains('img_art') == true) {
                              return UIImage(
                                assetImage: logic.productBean.cover ?? '',
                              );
                            }
                            return Image.file(File(logic.productBean.cover ?? ''));
                          }
                          return UIImage(
                            assetImage: logic.productBean.details?[index - 1] ?? '',
                          );
                        },
                        pagination: SwiperPagination(
                          builder: DotSwiperPaginationBuilder(
                            color: kAppColor('#EEEEEE'),
                            activeColor: kAppThemeColor,
                          ),
                        ));
                  }),
                ),
              ],
            ),
            UIText(
              padding: EdgeInsets.only(left: 20.w, right: 20.w, top: 32.h),
              text: logic.productBean.title ?? '',
              textColor: kAppTextColor,
              fontSize: 16.sp,
              fontWeight: FontWeight.bold,
              shrinkWrap: false,
            ),
            if (titleTranslated != null)
              UIText(
                margin: EdgeInsets.only(left: 20.w, right: 20.w, top: 5.h),
                decoration: BoxDecoration(border: Border(top: BorderSide(width: 1.w, color: kAppLineColor))),
                text: titleTranslated,
                textColor: kAppTextColor,
                fontSize: 16.sp,
                fontWeight: FontWeight.bold,
                shrinkWrap: false,
              ),
            UIText(
              padding: EdgeInsets.only(left: 20.w, right: 20.w, top: 16.h),
              text: logic.productBean.describe ?? '',
              textColor: kAppTextColor,
              fontSize: 13.sp,
              shrinkWrap: false,
            ),
            if (describeTranslated != null)
              UIText(
                margin: EdgeInsets.only(left: 20.w, right: 20.w, top: 5.h),
                decoration: BoxDecoration(border: Border(top: BorderSide(width: 1.w, color: kAppLineColor))),
                text: describeTranslated ?? '',
                textColor: kAppTextColor,
                fontSize: 13.sp,
                shrinkWrap: false,
              ),
            UIRow(
              margin: EdgeInsets.only(top: 16.h, bottom: 32.h),
              padding: EdgeInsets.symmetric(horizontal: 20.w),
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                if (titleTranslated == null || describeTranslated == null)
                  UIText(
                    padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 3.h),
                    text: 'Translate',
                    textColor: kAppTextColor,
                    fontSize: 11.sp,
                    radius: 4.w,
                    strokeWidth: 1.w,
                    strokeColor: kAppTextColor,
                    onTap: () {
                      logic.onTranslateForArtmixDetailTitle(logic.productBean);
                      logic.onTranslateForArtmixDetailDescribe(logic.productBean);
                    },
                  )
                else
                  Container(),
                GetBuilder<WhlProductDetailLogic>(builder: (logic) {
                  return UIImage(
                    assetImage: logic.productBean.isLike == true ? 'icon_like.png' : 'icon_like_no.png',
                    width: 16.w,
                    onTap: () {
                      logic.doClickProductLike(logic.productBean);
                    },
                  );
                })
              ],
            )
          ],
        ),
      );
    });
  }

  UIRow buildTopBar() {
    return UIRow(
      height: ScreenUtil().statusBarHeight + 44.h,
      width: double.maxFinite,
      gradientStartColor: Colors.transparent,
      gradientEndColor: Colors.black.withOpacity(0.3),
      gradientBegin: Alignment.topCenter,
      gradientEnd: Alignment.bottomCenter,
      padding: EdgeInsets.only(left: 16.w, right: 16.w, top: ScreenUtil().statusBarHeight),
      // height: 44.h,
      children: [
        UIImage(
          assetImage: 'icon_back_white_circle.png',
          width: 28.w,
          margin: EdgeInsets.only(right: 20.w),
          onTap: () {
            Get.back();
          },
        ),
        Expanded(
          child: UIRow(
            height: 36.h,
            radius: 100.w,
            padding: EdgeInsets.only(left: 2.w, right: 4.w),
            color: Colors.white.withOpacity(0.4),
            children: [
              UIImage(
                httpImage: logic.productBean.avatar ?? '',
                width: 32.h,
                height: 32.h,
                radius: 16.h,
                strokeWidth: 1.w,
                strokeColor: Colors.white,
                onTap: () {
                  logic.doClickAvatar();
                },
              ),
              Expanded(
                child: UIText(
                  margin: EdgeInsets.only(left: 8.w),
                  text: logic.productBean.nickname ?? '',
                  textColor: Colors.white,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                  maxLines: 1,
                  shrinkWrap: false,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              GetBuilder<WhlProductDetailLogic>(builder: (logic) {
                if (logic.productBean.userId == WhlUserUtils.getId()) return Container();
                if (logic.productBean.isFollowed ?? false) {
                  return UIText(
                    padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 8.h),
                    text: 'Followed',
                    textColor: Colors.white,
                    fontSize: 12.sp,
                    strokeColor: Colors.white,
                    strokeWidth: 1.w,
                    radius: 100.w,
                    onTap: () {
                      logic.doClickCancelFollow();
                    },
                  );
                } else {
                  return UIText(
                    padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 8.h),
                    text: 'Follow',
                    textColor: Colors.white,
                    fontSize: 12.sp,
                    gradientStartColor: kAppLeftColor,
                    gradientEndColor: kAppRightColor,
                    radius: 100.w,
                    onTap: () {
                      logic.doClickFollow();
                    },
                  );
                }
              })
            ],
          ),
        ),
        GetBuilder<WhlProductDetailLogic>(builder: (logic) {
          if (logic.productBean.userId != WhlUserUtils.getId() /*&& logic.productBean.isFollowed == true*/) {
            return UIImage(
              margin: EdgeInsets.only(left: 35.w),
              assetImage: 'icon_chat.png',
              width: 28.w,
              onTap: () {
                logic.doClickChat();
              },
            );
          } else {
            return Container();
          }
        }),
        if (logic.productBean.userId != WhlUserUtils.getId())
          UIImage(
            margin: EdgeInsets.only(left: 28.w),
            assetImage: 'icon_more_cicle.png',
            width: 28.w,
            imageColor: Colors.white,
            onTap: () {
              logic.doClickMore();
            },
          )
      ],
    );
  }
}
